<template>
  <div class="user">
    <!-- 内容区域 start-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="5">
          <!-- <el-input placeholder="请输入内容" size="mini" clearable @clear="getUserList"> -->
          <!--  v-model="queryInfo.query" -->
          <!-- <el-button slot="append" icon="el-icon-search" size="mini" @click="getUserList"></el-button>
          </el-input>-->
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="mini" @click="dialog = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 管理员列表区域 start-->
      <el-table :data="adminList" border size="small">
        <el-table-column align="center" label="#" type="index"></el-table-column>
        <el-table-column align="center" label="头像" prop="admin_avatar">
          <template slot-scope="scope">
            <el-avatar
              v-if="scope.row.admin_avatar"
              shape="circle"
              :size="50"
              :src="scope.row.admin_avatar"
            ></el-avatar>
          </template>
        </el-table-column>
        <el-table-column align="center" label="账号名称" prop="admin_name"></el-table-column>
        <el-table-column align="center" label="邮箱" prop="admin_email"></el-table-column>
        <el-table-column align="center" label="电话" prop="admin_tel"></el-table-column>
        <el-table-column align="center" label="当前角色" prop="admin_role">
          <template slot-scope="scope">
            <el-tag>{{scope.row.admin_role}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户状态" prop="admin_status">
          <template slot-scope="scope">
            <el-switch
              :active-color="activeColor"
              :value="scope.row.admin_status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="停用"
              v-model="scope.row.admin_status"
              @change="changeAdminState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后登录时间" prop="last_loginTime"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditAdminDialog(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteAdminDialog(scope.row)"
            ></el-button>
            <!-- <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top-start"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-s-tools" size="mini"></el-button>
            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>
      <!-- 管理员列表区域 end-->

      <!-- 分页 -->
      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>-->
      <!-- 抽屉功能 start-->
      <el-drawer
        title="新增管理员"
        :before-close="handleClose"
        :visible.sync="dialog"
        :with-header="false"
        custom-class="demo-drawer"
        ref="drawer"
      >
        <div class="drawer_content">
          <h3>新增管理员信息</h3>
          <el-form
            :inline="true"
            label-width="auto"
            :model="setAdminform"
            ref="setAdminform"
            size="mini"
          >
            <el-form-item label="头像" prop="admin_avatar">
              <el-upload
                class="avatar-uploader"
                :action="$config.imgUpload"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="avatarImg" :src="avatarImg" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="账号名称" prop="admin_name">
              <el-input v-model="setAdminform.admin_name"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="admin_password">
              <el-input v-model="setAdminform.admin_password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="admin_email">
              <el-input v-model="setAdminform.admin_email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="admin_tel">
              <el-input v-model="setAdminform.admin_tel"></el-input>
            </el-form-item>
            <el-form-item label="当前角色" prop="admin_role">
              <el-select size="mini" v-model="setAdminform.admin_role" placeholder="选择角色">
                <el-option
                  v-for="item in rolesList"
                  :key="item._id"
                  :label="item.role_name"
                  :value="item.role_name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="管理员状态" prop="admin_status">
              <el-input :disabled="true" v-model="setAdminform.admin_status"></el-input>
            </el-form-item>
          </el-form>
          <div class="drawer_footer">
            <el-button @click="cancelForm" size="mini">取 消</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="setAdmin"
              :loading="loading"
            >{{ loading ? '提交中 ...' : '确 定' }}</el-button>
          </div>
        </div>
      </el-drawer>
      <!-- 抽屉功能 end-->
    </el-card>

    <!-- 编辑管理员 start-->
    <EditAdminDialog
      :editAdminFormCom="editAdminFormCom"
      :rolesList="rolesList"
      @confirmEditAdmin="confirmEditAdmin"
    ></EditAdminDialog>
    <!-- 编辑管理员 end -->
  </div>
</template>

<script>
import utils from '@/plugins/utils'
import { mapGetters } from 'vuex'

export default {
  components: {
    EditAdminDialog: () => import('@/components/Dialogs/EditAdmin.vue')
  },
  props: {},
  data() {
    return {
      // queryInfo: {
      //   //管理员数据列表请求参数
      //   query: '', //查询参数
      //   pagenum: 1, //当前页码
      //   pagesize: 4 //每页显示条数
      // },
      // total: 0, //列表数据总条数
      activeColor: '#13ce66', //状态开关颜色
      dialog: false, //控制抽屉的隐藏和显示
      loading: false,
      avatarImg: '', //管理员头像预览
      // rolesList: '', //管理员角色选择
      //新增管理员信息表单
      setAdminform: {
        admin_name: '', //管理员名字
        admin_password: '', //管理员密码
        admin_email: '', //管理员邮箱
        admin_avatar: '', //管理员头像
        admin_tel: '', //管理员电话
        admin_role: '', //管理员角色
        admin_status: 1 //管理员状态
      },
      headers: {
        Authorization: `Bearer ${utils.local.get('userToken')}` //设置头像上传的请求头部
      },
      editAdminFormCom: {
        editAdminForm: {}, //编辑管理员表单
        editAdminDialogVisible: false //编辑管理员弹框默认状态
      }
    }
  },
  created() {
    this.getAdminList()
  },
  computed: {
    ...mapGetters(['adminList', 'rolesList'])
  },
  methods: {
    //新增管理员信息
    async setAdmin() {
      const {
        admin_name,
        admin_password,
        admin_email,
        admin_avatar,
        admin_tel,
        admin_role,
        status
      } = this.setAdminform
      const { data: res } = await this.$api.admin.setAdmin(this.setAdminform)
      if (res.meta.status !== 200) {
        this.$message.error({ message: res.meta.message }) //当前管理员设置保存失败
      } else {
        this.$refs.setAdminform.resetFields() //重置表单内容
        this.avatarImg = '' //重置头像预览
        this.$message.success({ message: res.meta.message }) //当前管理员设置保存成功
        this.$store.dispatch('getadminList')
      }
    },

    //头像上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) this.$message.error('上传头像图片只能是 JPG 格式!')
      if (!isLt2M) this.$message.error('上传头像图片大小不能超过 2MB!')
      return isJPG && isLt2M
    },

    //头像上传成功后
    handleAvatarSuccess(res, file) {
      this.$message.success({ message: res.meta.message })
      this.avatarImg = URL.createObjectURL(file.raw)
      this.setAdminform.admin_avatar = res.data.filename
    },

    //获取管理员列表请求
    async getAdminList() {
      this.$store.dispatch('getrolesList')
      if (!utils.local.get('adminList')) {
        const { data: res } = await this.$api.admin.adminList()
        if (res.meta.status !== 200) {
          this.$message.error({ message: res.meta.message })
        } else {
          this.$store.commit('adminList', res.data)
          // this.total = res.data.total
        }
      }
    },

    //修改管理员状态
    async changeAdminState(adminState) {
      const { data: res } = await this.$api.admin.adminState({
        _id: adminState._id, //管理员ID
        admin_name: adminState.admin_name, //管理员名称
        admin_status: adminState.admin_status //管理员状态
      })
      if (res.meta.status !== 200) {
        adminState.admin_status = !adminState.admin_status
        this.$message.error({ message: res.meta.message }) //当前管理员设置保存失败
      } else {
        this.$message.success({ message: res.meta.message }) //当前管理员状态修改成功
        this.$store.dispatch('getadminList')
      }
    },

    //编辑管理员对话框点击显示事件
    showEditAdminDialog(admin) {
      const data = {
        _id: admin._id,
        admin_name: admin.admin_name,
        admin_email: admin.admin_email,
        admin_tel: admin.admin_tel,
        admin_role: admin.admin_role
      }
      this.editAdminFormCom.editAdminForm = data //父组件传值子组件
      this.editAdminFormCom.editAdminDialogVisible = true
    },

    //编辑管理员对话框的提交事件
    async confirmEditAdmin(data) {
      const { data: res } = await this.$api.admin.putEditAdmin(data)
      if (res.meta.status !== 200) {
        return this.$message.error({ message: res.meta.message })
      } else {
        this.$message.success({ message: res.meta.message })
        this.$store.dispatch('getadminList')
      }
    },

    //删除选中管理员
    async deleteAdminDialog(del) {
      await this.$confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$api.admin.deleteAdmin({
            _id: del._id
          })
          if (res.meta.status !== 200) {
            return this.$message.error({ message: res.meta.message })
          } else {
            this.$message.success({ message: res.meta.message })
            this.$store.dispatch('getadminList')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消管理员删除'
          })
        })
    },

    //抽屉功能
    handleClose() {
      this.loading = false
      this.dialog = false
    },

    cancelForm() {
      this.loading = false
      this.dialog = false
    }

    //页码大小
    // handleSizeChange(newSize) {
    //   this.queryInfo.pagesize = newSize
    //   this.getUserList()
    // },

    //当前页变动
    // handleCurrentChange(newPage) {
    //   this.queryInfo.pagenum = newPage
    //   this.getUserList()
    // },
  }
}
</script>
<style lang="sass" scoped>
.drawer_content
  padding-left: 15px
  .el-form
    width: 600px
    padding: 15px
    .el-input,.el-select,.avatar-uploader
      width: 150px

.el-drawer
  outline: none
  height: 100%

.demo-drawer__footer
  margin-left: 20px
</style>